<template>
  <span
    ref="textRef"
    :class="+props.maxLines === 1 ? 'truncate' : 'cps-text-ellipsis'"
    v-bind="$attrs"
    :style="{
      '-webkit-line-clamp': +props.maxLines,
      'line-clamp': +props.maxLines
    }"
    @mouseleave="handleMouseout"
    @mouseenter="handleMouseover"
  >
    <slot></slot>
  </span>
  <teleport to="body">
    <div
      v-if="showTooltip"
      style="position: absolute; top: 0px; left: 0px; width: 100%"
    >
      <div>
        <div
          class="ant-tooltip ant-tooltip-placement-top"
          :style="tooltipStyle"
          style="transform: translate(-50%, -50%)"
        >
          <div class="ant-tooltip-content">
            <div class="ant-tooltip-arrow">
              <span class="ant-tooltip-arrow-content"></span>
            </div>
            <div class="ant-tooltip-inner" role="tooltip">
              <slot v-if="!props.toopTipContent"></slot>
              <span v-else>{{ props.toopTipContent }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </teleport>
</template>

<script setup>
import { throttle } from 'lodash-es'
import { ref } from 'vue'
const props = defineProps({
  toopTipContent: {
    type: String
  },
  maxLines: {
    type: Number,
    default: 1
  }
})
const textRef = ref(null)
const showTooltip = ref(false)
const tooltipStyle = ref({})

const getMousePosition = () => {
  const rect = textRef.value.getBoundingClientRect()
  tooltipStyle.value = {
    left: ''.concat(rect.left + rect.width / 2, 'px'),
    top: ''.concat(rect.top - rect.height, 'px')
  }
}

const handleMouseover = throttle(e => {
  const domNode = textRef.value
  if (!domNode) return false

  getMousePosition(e)
  if (props.maxLines === 1) {
    showTooltip.value = domNode.offsetWidth < domNode.scrollWidth
  } else {
    const lineHeight = parseFloat(window.getComputedStyle(domNode).lineHeight)
    const maxHeight = lineHeight * props.maxLines
    showTooltip.value =
      domNode.offsetHeight < domNode.scrollHeight ||
      domNode.offsetHeight > maxHeight
  }
}, 200)
const handleMouseout = throttle(() => {
  showTooltip.value = false
}, 200)
</script>

<style scoped>
.ant-tooltip-arrow-content,
.ant-tooltip-inner {
  background-color: rgba(0, 0, 0, 0.75);
}
.cps-text-ellipsis {
  overflow: hidden;
  -webkit-box-orient: vertical;
  box-orient: vertical;
  display: -webkit-box;
  display: box;
}
</style>
